#include <glog/logging.h>
#include <glog/log_severity.h>

#include "parser.h"
#include "request_type.h"
#include "jsoncpp/json.h"

Parser::Parser()
{ 
	LOG(INFO)<<"Parser::Parser";
}

Parser::~Parser()
{ 
	LOG(INFO)<<"Parser::~~Parser";
}
	
event_type_e Parser::ParseEvent(const char *buffer, std::string &id, std::string &peer_id, int &type, std::string &content)
{
	event_type_e event_code = EVENT_TYPE_INVALID;
	int seq = 0;

	Json::Reader reader;
	Json::Value value;

	if(!reader.parse(buffer, value))
	{
		LOG(ERROR)<<"Parser::parse_request error : json parse error!";
		
		return EVENT_TYPE_INVALID;
	}

	if(!value["event"].isNull())
	{
		event_code = static_cast<event_type_e>(value["event"].asInt());

		if(!value["seq"].isNull())
		{
			seq = value["seq"].asInt();
		}

		if(!value["type"].isNull())
		{
			type = value["type"].asInt();
		}

		if(!value["msg"].isNull())
		{
			std::string msg = value["msg"].asString();
			content = msg;

			LOG(ERROR)<<"parse_event, msg: "<<msg;
		}

		if(!value["id"].isNull())
		{
			id = value["id"].asString();
		}

		if(!value["peer_id"].isNull())
		{
			peer_id = value["peer_id"].asString();
		}

		LOG(INFO)<<"Parser::ParseEvent, seq: "<<seq<<", event_code: "<<event_code<<", id: "<<id<<", peer_id: "<<", content: "<<content;
	}
	else
	{
		LOG(ERROR)<<"Parser::parse_request error : invalid json message !!!";
		
		return EVENT_TYPE_INVALID;
	}

	return event_code;
}

